<template>
	<view class="container">
		<!-- 页面标题 -->
		<view class="header">
			<view class="back-icon" @click="goBack">
				<text class="iconfont">&#xe600;</text>
			</view>
			<view class="title">申请租赁</view>
		</view>
		
		<!-- 房源信息 -->
		<view class="housing-info">
			<view class="section-title">房源信息</view>
			
			<view class="info-item">
				<text class="label">单元编号</text>
				<text class="value">{{ housing.unit_number }}</text>
			</view>
			
			<view class="info-item">
				<text class="label">所在位置</text>
				<text class="value">{{ housing.building.name }} {{ housing.floor ? housing.floor.actual_label : '' }}</text>
			</view>
			
			<view class="info-item">
				<text class="label">单元类型</text>
				<text class="value">{{ housing.unit_type }}</text>
			</view>
			
			<view class="info-item">
				<text class="label">实际面积</text>
				<text class="value">{{ housing.actual_area }} ㎡</text>
			</view>
			
			<view class="info-item">
				<text class="label">租金</text>
				<text class="value price">{{ housing.rental_price }} 元/㎡/月</text>
			</view>
		</view>
		
		<!-- 申请表单 -->
		<view class="application-form">
			<view class="section-title">申请信息</view>
			
			<!-- 企业选择 -->
			<view class="form-item" v-if="userInfo && userInfo.userType === 'company_employee'">
				<text class="form-label">申请企业</text>
				<view class="form-input">
					<picker @change="onCompanyChange" :value="companyIndex" :range="companyNames">
						<view class="picker-value">{{ companyNames[companyIndex] || '请选择企业' }}</view>
					</picker>
				</view>
			</view>
			
			<!-- 租期开始日期 -->
			<view class="form-item">
				<text class="form-label">开始日期</text>
				<view class="form-input">
					<picker mode="date" :value="formData.expected_start_date" @change="onStartDateChange" :start="minDate">
						<view class="picker-value">{{ formData.expected_start_date || '请选择开始日期' }}</view>
					</picker>
				</view>
			</view>
			
			<!-- 租期时长 -->
			<view class="form-item">
				<text class="form-label">租期</text>
				<view class="form-input">
					<picker @change="onDurationChange" :value="durationIndex" :range="durations">
						<view class="picker-value">{{ durations[durationIndex] || '请选择租期' }}</view>
					</picker>
				</view>
			</view>
			
			<!-- 联系人 -->
			<view class="form-item">
				<text class="form-label">联系人</text>
				<view class="form-input">
					<input type="text" v-model="formData.contact_name" placeholder="请输入联系人姓名" />
				</view>
			</view>
			
			<!-- 联系电话 -->
			<view class="form-item">
				<text class="form-label">联系电话</text>
				<view class="form-input">
					<input type="text" v-model="formData.contact_phone" placeholder="请输入联系电话" />
				</view>
			</view>
			
			<!-- 备注 -->
			<view class="form-item">
				<text class="form-label">备注</text>
				<view class="form-input">
					<textarea v-model="formData.remarks" placeholder="请输入备注信息（选填）" />
				</view>
			</view>
		</view>
		
		<!-- 租赁须知 -->
		<view class="notice-section">
			<view class="section-title">租赁须知</view>
			<view class="notice-list">
				<view class="notice-item">
					<text class="dot"></text>
					<text class="text">租金按月支付，物业费按季度支付</text>
				</view>
				<view class="notice-item">
					<text class="dot"></text>
					<text class="text">需缴纳相当于两个月租金的押金</text>
				</view>
				<view class="notice-item">
					<text class="dot"></text>
					<text class="text">最短租期为一年</text>
				</view>
				<view class="notice-item">
					<text class="dot"></text>
					<text class="text">申请提交后，工作人员将在1-3个工作日内审核</text>
				</view>
			</view>
			
			<view class="agreement">
				<checkbox-group @change="onAgreementChange">
					<label class="agreement-label">
						<checkbox :checked="formData.agreement" color="#007AFF" />
						<text>我已阅读并同意《租赁协议》</text>
					</label>
				</checkbox-group>
			</view>
		</view>
		
		<!-- 提交按钮 -->
		<view class="submit-section">
			<button class="submit-btn" :disabled="!formData.agreement" @click="submitApplication">提交申请</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// API基础URL
				baseURL: 'http://localhost:8000',
				
				id: null,
				housing: {},
				userInfo: null,
				
				// 企业选择
				companies: [],
				companyNames: [],
				companyIndex: 0,
				
				// 租期选择
				durations: ['12个月', '24个月', '36个月', '48个月', '60个月'],
				durationValues: [12, 24, 36, 48, 60],
				durationIndex: 0,
				
				// 表单数据
				formData: {
					unit_id: '',
					company_id: '',
					expected_start_date: '',
					expected_duration: 12,
					contact_name: '',
					contact_phone: '',
					remarks: '',
					agreement: false
				},
				
				// 最小日期（明天）
				minDate: ''
			}
		},
		onLoad(options) {
			this.id = options.id
			this.formData.unit_id = this.id
			
			// 设置最小日期为明天
			const tomorrow = new Date()
			tomorrow.setDate(tomorrow.getDate() + 1)
			this.minDate = this.formatDate(tomorrow)
			this.formData.expected_start_date = this.minDate
			
			// 获取用户信息
			this.getUserInfo()
			
			// 从缓存获取房源详情
			const housingDetail = uni.getStorageSync('currentHousingDetail')
			if (housingDetail && housingDetail.unit_id == this.id) {
				this.housing = housingDetail
			} else {
				// 如果缓存中没有，则从服务器获取
				this.fetchHousingDetail()
			}
			
			// 如果是企业员工，获取企业列表
			if (this.userInfo && this.userInfo.userType === 'company_employee') {
				this.fetchCompanies()
			}
		},
		methods: {
			// 获取用户信息
			getUserInfo() {
				const userInfo = uni.getStorageSync('userInfo')
				if (userInfo) {
					this.userInfo = userInfo
					this.formData.contact_name = userInfo.name || ''
					this.formData.contact_phone = userInfo.phone || ''
				} else {
					// 未登录跳转到登录页
					uni.showModal({
						title: '提示',
						content: '请先登录',
						showCancel: false,
						success: () => {
							uni.reLaunch({
								url: '/pages/login/login'
							})
						}
					})
				}
			},
			
			// 从服务器获取房源详情
			fetchHousingDetail() {
				uni.showLoading({
					title: '加载中'
				})
				
				uni.request({
					url: `http://localhost:8000/api/assets/units/${this.id}/`,
					method: 'GET',
					header: {
						'Authorization': 'Bearer ' + uni.getStorageSync('token')
					},
					success: (res) => {
						uni.hideLoading()
						
						if (res.data.code === 200) {
							this.housing = res.data.data
						} else {
							uni.showToast({
								title: res.data.message || '获取房源详情失败',
								icon: 'none'
							})
						}
					},
					fail: (err) => {
						uni.hideLoading()
						console.error('获取房源详情失败', err)
						uni.showToast({
							title: '获取房源详情失败',
							icon: 'none'
						})
					}
				})
			},
			
			// 获取企业列表
			fetchCompanies() {
				uni.request({
					url: 'http://localhost:8000/api/users/companies/',
					method: 'GET',
					header: {
						'Authorization': 'Bearer ' + uni.getStorageSync('token')
					},
					success: (res) => {
						if (res.data.code === 200) {
							this.companies = res.data.data.list || []
							this.companyNames = this.companies.map(item => item.name)
							
							// 如果用户有关联企业，默认选中
							if (this.userInfo.company) {
								const index = this.companies.findIndex(item => item.id === this.userInfo.company.id)
								if (index !== -1) {
									this.companyIndex = index
									this.formData.company_id = this.companies[index].id
								}
							}
						}
					},
					fail: (err) => {
						console.error('获取企业列表失败', err)
					}
				})
			},
			
			// 格式化日期为YYYY-MM-DD
			formatDate(date) {
				const year = date.getFullYear()
				const month = (date.getMonth() + 1).toString().padStart(2, '0')
				const day = date.getDate().toString().padStart(2, '0')
				return `${year}-${month}-${day}`
			},
			
			// 企业选择变化
			onCompanyChange(e) {
				this.companyIndex = e.detail.value
				this.formData.company_id = this.companies[this.companyIndex].id
			},
			
			// 开始日期变化
			onStartDateChange(e) {
				this.formData.expected_start_date = e.detail.value
			},
			
			// 租期变化
			onDurationChange(e) {
				this.durationIndex = e.detail.value
				this.formData.expected_duration = this.durationValues[this.durationIndex]
			},
			
			// 协议勾选变化
			onAgreementChange(e) {
				this.formData.agreement = e.detail.value.length > 0
			},
			
			// 返回上一页
			goBack() {
				uni.navigateBack()
			},
			
			// 提交申请
			submitApplication() {
				// 表单验证
				if (!this.formData.expected_start_date) {
					uni.showToast({
						title: '请选择开始日期',
						icon: 'none'
					})
					return
				}
				
				if (!this.formData.contact_name) {
					uni.showToast({
						title: '请输入联系人姓名',
						icon: 'none'
					})
					return
				}
				
				if (!this.formData.contact_phone) {
					uni.showToast({
						title: '请输入联系电话',
						icon: 'none'
					})
					return
				}
				
				// 企业员工必须选择企业
				if (this.userInfo.userType === 'company_employee' && !this.formData.company_id) {
					uni.showToast({
						title: '请选择申请企业',
						icon: 'none'
					})
					return
				}
				
				// 显示确认弹窗
				uni.showModal({
					title: '确认提交',
					content: '确定要提交租赁申请吗？',
					success: (res) => {
						if (res.confirm) {
							this.doSubmit()
						}
					}
				})
			},
			
			// 执行提交
			doSubmit() {
				uni.showLoading({
					title: '提交中'
				})
				
				// 构建请求数据
				const requestData = {
					unit_id: this.formData.unit_id,
					expected_start_date: this.formData.expected_start_date,
					expected_duration: this.formData.expected_duration,
					contact_name: this.formData.contact_name,
					contact_phone: this.formData.contact_phone,
					remarks: this.formData.remarks
				}
				
				// 如果是企业员工且选择了企业，添加企业ID
				if (this.userInfo.userType === 'company_employee' && this.formData.company_id) {
					requestData.company_id = this.formData.company_id
				}
				
				// 发送请求
				uni.request({
					url: this.baseURL + '/api/services/leasing-applications/add/',
					method: 'POST',
					header: {
						'Authorization': 'Bearer ' + uni.getStorageSync('token'),
						'Content-Type': 'application/json'
					},
					data: requestData,
					success: (res) => {
						uni.hideLoading()
						
						if (res.data.code === 201) {
							uni.showToast({
								title: '申请提交成功',
								icon: 'success'
							})
							
							// 延迟跳转到申请列表页
							setTimeout(() => {
								uni.redirectTo({
									url: '/pages/services/housing/applications'
								})
							}, 1500)
						} else {
							uni.showToast({
								title: res.data.message || '申请提交失败',
								icon: 'none'
							})
						}
					},
					fail: (err) => {
						uni.hideLoading()
						console.error('申请提交失败', err)
						uni.showToast({
							title: '申请提交失败，请稍后重试',
							icon: 'none'
						})
					}
				})
			}
		}
	}
</script>

<style>
	.container {
		padding-bottom: 120rpx; /* 为底部按钮留出空间 */
	}
	
	.header {
		position: relative;
		background-color: #FFFFFF;
		padding: 30rpx;
		border-bottom: 1px solid #EEEEEE;
		display: flex;
		align-items: center;
	}
	
	.back-icon {
		position: absolute;
		left: 30rpx;
		font-size: 36rpx;
		color: #333333;
	}
	
	.title {
		flex: 1;
		text-align: center;
		font-size: 36rpx;
		font-weight: bold;
		color: #333333;
	}
	
	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
		margin-bottom: 20rpx;
		position: relative;
		padding-left: 20rpx;
	}
	
	.section-title::before {
		content: '';
		position: absolute;
		left: 0;
		top: 8rpx;
		width: 8rpx;
		height: 32rpx;
		background-color: #007AFF;
		border-radius: 4rpx;
	}
	
	.housing-info {
		background-color: #FFFFFF;
		padding: 30rpx;
		margin: 20rpx;
		border-radius: 10rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
	}
	
	.info-item {
		display: flex;
		padding: 16rpx 0;
		border-bottom: 1px solid #F5F5F5;
	}
	
	.info-item:last-child {
		border-bottom: none;
	}
	
	.label {
		width: 160rpx;
		font-size: 28rpx;
		color: #666666;
	}
	
	.value {
		flex: 1;
		font-size: 28rpx;
		color: #333333;
	}
	
	.price {
		color: #FF5151;
		font-weight: bold;
	}
	
	.application-form {
		background-color: #FFFFFF;
		padding: 30rpx;
		margin: 20rpx;
		border-radius: 10rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
	}
	
	.form-item {
		margin-bottom: 30rpx;
	}
	
	.form-label {
		display: block;
		font-size: 28rpx;
		color: #333333;
		margin-bottom: 10rpx;
	}
	
	.form-input {
		background-color: #F8F8F8;
		border-radius: 8rpx;
		padding: 0 20rpx;
	}
	
	.form-input input {
		height: 80rpx;
		font-size: 28rpx;
	}
	
	.form-input textarea {
		width: 100%;
		height: 160rpx;
		padding: 20rpx 0;
		font-size: 28rpx;
	}
	
	.picker-value {
		height: 80rpx;
		line-height: 80rpx;
		font-size: 28rpx;
		color: #333333;
	}
	
	.notice-section {
		background-color: #FFFFFF;
		padding: 30rpx;
		margin: 20rpx;
		border-radius: 10rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
	}
	
	.notice-list {
		margin-bottom: 30rpx;
	}
	
	.notice-item {
		display: flex;
		align-items: flex-start;
		margin-bottom: 16rpx;
	}
	
	.dot {
		width: 12rpx;
		height: 12rpx;
		background-color: #007AFF;
		border-radius: 50%;
		margin-top: 12rpx;
		margin-right: 16rpx;
	}
	
	.text {
		flex: 1;
		font-size: 28rpx;
		color: #666666;
		line-height: 1.6;
	}
	
	.agreement {
		padding: 20rpx 0;
	}
	
	.agreement-label {
		display: flex;
		align-items: center;
		font-size: 28rpx;
		color: #333333;
	}
	
	.agreement-label text {
		margin-left: 10rpx;
	}
	
	.submit-section {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #FFFFFF;
		padding: 20rpx 30rpx;
		box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
	}
	
	.submit-btn {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		background-color: #007AFF;
		color: #FFFFFF;
		font-size: 30rpx;
		border-radius: 40rpx;
	}
	
	.submit-btn[disabled] {
		background-color: #CCCCCC;
		color: #FFFFFF;
	}
</style> 